package com.young.cloud.gateway;

import com.young.common.util.CommonConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.client.RestTemplate;

/**
 * Created by Administrator on 2019/12/28 0028.
 */
@SpringBootApplication
@EnableEurekaClient
@ComponentScan("com.young")
@EnableFeignClients("com.young")
@EnableZuulProxy
public class GatewayApplication {

    private static final Logger logger = LoggerFactory.getLogger(GatewayApplication.class);

    /**
     * 程序入口，启动springboot
     * @param args
     */
    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
        logger.info("[统一网关] 统一网关启动完成.");
    }

    /**
     * feign需要声明RestTemplate
     * @return
     */
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    /**
     * 通过拦截器在rpc调用时传递traceId
     * @return
     */
    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
             @Override
            public void apply(RequestTemplate template) {
                //添加链路id的header
                template.header(CommonConstants.TRACE_KEY, MDC.get(CommonConstants.TRACE_KEY));
            }
        };
    }


}
